<template>
    <!--立项议题-->
    <public-dialog
        title="立项议题"
        width="60%"
        v-model:visible="visible"
        confirm-button-title="送审"
        :confirm-disabled="isLoading"
        :footer-button="state.type==='submit'"
        @on-confirm="onConfirm"
    >
        <template #default>
            <el-main
                v-loading="isLoading"
                :element-loading-text="loadingTitle"
            >
                <el-form
                    ref="formRef"
                    :model="form"
                    :rules="state.type==='submit'?rules:null"
                    label-width="120px"
                    :disabled="state.type==='query'"
                >
                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="所属项目">
                                <el-input disabled :placeholder="form.projectName"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2"></el-col>
                        <el-col :span="11">
                            <el-form-item label="所属部门" prop="applyDepartmentId">
                                <el-select
                                    clearable class="input-width"
                                    v-model="form.applyDepartmentId"
                                    @change="departmentChange"
                                >
                                    <el-option v-for="(item,index) in data.allDepartmentList" :key="index" :label="item.departmentName" :value="item.departmentId"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="会审部门" prop="reviewDepartmentId">
                                <el-select
                                    clearable class="input-width"
                                    v-model="form.reviewDepartmentId"
                                >
                                    <el-option v-for="(item,index) in data.allDepartmentList" :key="index" :label="item.departmentName" :value="item.departmentId"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2"></el-col>
                        <el-col :span="11">
                            <el-form-item label="申请人" prop="applyUserId">
                                <el-select
                                    v-if="state.type==='submit'"
                                    clearable class="input-width"
                                    v-model="form.applyUserId"
                                >
                                    <el-option v-for="(item,index) in state.departmentPersonList" :key="index" :label="item.userName" :value="item.userId"></el-option>
                                </el-select>
                                <el-input v-if="state.type === 'query'" :placeholder="form.applyUserName"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="议题名称" prop="name">
                                <el-input v-model="form.name" placeholder="请输入会议议题"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2"></el-col>
                        <el-col :span="11">
                            <el-form-item label="议题简述" prop="summary">
                                <el-input v-model="form.summary" placeholder="请输入议题简述"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="议题性质" prop="type">
                                <el-select
                                    clearable class="input-width"
                                    v-model="form.type"
                                >
                                    <el-option label="三种一大" :value="0"></el-option>
                                    <el-option label="非三种一大" :value="1"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2"></el-col>
                        <el-col :span="11">
                            <el-form-item label="紧急程度" prop="urgency">
                                <el-select
                                    clearable class="input-width"
                                    v-model="form.urgency"
                                >
                                    <el-option label="普通" :value="1"></el-option>
                                    <el-option label="加急" :value="2"></el-option>
                                    <el-option label="平急" :value="3"></el-option>
                                    <el-option label="特急" :value="4"></el-option>
                                    <el-option label="特提" :value="5"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="11">
                            <el-form-item label="人事议题" prop="isPersonnel">
                                <el-select
                                    clearable class="input-width"
                                    v-model="form.isPersonnel"
                                >
                                    <el-option label="不是" :value="-1"></el-option>
                                    <el-option label="是" :value="1"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2"></el-col>
                        <el-col :span="11">
                            <el-form-item label="律师意见" prop="opinionFiles">
                                <el-upload
                                    v-if="state.type==='submit'"
                                    ref="uploadRef"
                                    action="#"
                                    multiple
                                    :limit="9"
                                    :http-request="uploadFile"
                                    :on-remove="onRemove"
                                >
                                    <el-button style="background-color: #fff8f6;border-color: #FC7018;color: #FC7018;">
                                        <svg-icon icon-class="project-detail-icon-l-shangchuan" class="upload-icon m-r5"></svg-icon>
                                        点击上传
                                    </el-button>
                                </el-upload>
                                <div class="d-flex flex-column" v-if="state.type==='query'">
                                    <span
                                        class="m-b5 download-icon"
                                        v-for="(item,index) in form.opinionFiles" :key="index"
                                        @click="download(index)"
                                    >{{item.fileName}}</span>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="state.type === 'query'">
                        <el-col :span="11">
                            <el-form-item label="审批状态">
                                <el-input placeholder="同意"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2"></el-col>
                        <el-col :span="11">

                        </el-col>
                    </el-row>
                    <el-row v-if="state.type === 'query'">
                        <el-col :span="24">
                           <el-form-item label="审批意见">
                               <el-input type="textarea" :rows="5" :placeholder="form.opinion"></el-input>
                           </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-main>
        </template>
    </public-dialog>
</template>

<script setup>
import PublicDialog from "@/components/PublicDialog.vue";
import {inject, nextTick, reactive, ref} from "vue";
import {
    ElForm,
    ElFormItem,
    ElRow,
    ElCol,
    ElSelect,
    ElOption,
    ElMain,
    ElLoading,
    ElMessage,
    ElUpload, ElInput
} from "element-plus";
import {department} from "@/api/project";
import {reserveInvestmentProjectLibraryApi} from "@/api/investment";
import {exportFile, resetForm} from "@/common/utils/GlobalUtils";

const data = inject('state');
const isLoading = ref(false);
const loadingTitle = ref('数据提交中……');
const visible = ref(false);
const form = reactive({
    projectId: '',
    projectName:'',
    projectSetName:'',
    projectTypeName:'',
    applyUserName:'',
    applyDepartmentId: '',
    applyUserId: '',
    reviewDepartmentId: '',
    name: '',
    summary:'',
    type:'',
    urgency:'',
    isPersonnel:'',
    opinionFiles:[],
    opinion:''
});

const state = reactive({
    departmentPersonList:[],
    type:'submit'
});

const rules = reactive({
    applyDepartmentId: [
        { required: true, message: '请选择所属部门', trigger: 'change' },
    ],
    applyUserId: [
        { required: true, message: '请选择申请人', trigger: 'change' },
    ],
    reviewDepartmentId: [
        { required: true, message: '请选择会审部门', trigger: 'change' },
    ],
    isPersonnel: [
        { required: true, message: '请选择人事议题', trigger: 'change' },
    ],
});

/**
 * 根据部门id查负责人
 * @param responsibleDepartmentId
 */
const getLeaderByDepartmentId = (responsibleDepartmentId) => {
    department.getLeaderByDepartmentId(responsibleDepartmentId).then((res) => {
        const { code, msg } = res;
        if (code == 200) {
            state.departmentPersonList = res.data;
        }
    });
};

/**
 * 根据部门查底下的人
 * @param e
 */
const departmentChange = (e) => {
    if(e){
        getLeaderByDepartmentId(e);
    }
}

/**
 * 弹窗确认按钮
 */
const formRef = ref(null);
const emits = defineEmits(['onSuccess']);
const onConfirm = () => {
    formRef.value.validate((valid, fields) => {
        if (valid) {
            loadingTitle.value = '数据提交中……';
            isLoading.value = true;
            reserveInvestmentProjectLibraryApi.saveProjectMeeting(form).then(res=>{
                if(res.code == 200){
                    isLoading.value = false;
                    visible.value = false;
                    ElMessage.success('提交成功!');
                    resetForm(form);
                    formRef.value.resetFields();
                    emits('onSuccess');
                }
            });
        } else {
            console.log('error submit!', fields)
        }
    })
}

/**
 * el-upload 选择文件后的事件
 * @param file
 */
const uploadRef = ref(null);
const uploadFile =async (file) => {
    try{
        let uploadFile = new FormData();
        uploadFile.append("file",file.file);

        const addTypeArray = file.file.name.split(".");
        const addType = addTypeArray[addTypeArray.length - 1]
        if(addType === "doc" || addType === "docx" || addType === "word"){
            loadingTitle.value = '上传文件中...';
            isLoading.value = true;
            const res = await reserveInvestmentProjectLibraryApi.upload(uploadFile);
            if(res.code == 200){
                form.opinionFiles.push(res.data);
                isLoading.value = false;
            }
        }else{
            ElMessage.error('请上传正确格式的文档!');
            uploadRef.value.handleRemove(file);
        }
    }catch (e) {
        isLoading.value = false;
        ElMessage.warning('文件上传失败!');
    }

}

/**
 * el-upload 移除
 */
const onRemove = (e) => {
    form.opinionFiles.forEach((item,index)=>{
        if(item.split('-')[item.split('-').length-1] === e.name){
            form.opinionFiles.splice(index,1);
        }
    });
};

/**
 * 初始化赋值
 * @param data1
 * @param data2
 */
const _init = (data1,data2) => {
    for (let k1 in data1){
        for (let k2 in data2){
            if(k1 === k2){
                data1[k2] = data2[k1];
            }
        }
    }
}

/**
 * 查看项目议题
 * @param projectId
 */
const getProjectMeeting = (projectId) => {
    reserveInvestmentProjectLibraryApi.getProjectMeeting(projectId).then(res=>{
        if(res.code == 200){
            _init(form,res.data);
        }
    });
}

/**
 * 展示弹窗
 * @param data
 */
const open = (data,type) => {
    state.type = type;
    isLoading.value = false;

    if(data && type==='submit'){
        setTimeout(()=>{
            formRef.value.resetFields();
            uploadRef.value.clearFiles();
            form.projectName = data.projectName;
            form.projectId = data.projectId;
        },500);
    }
    if(data && type === 'query'){
        getProjectMeeting(data.projectId);
    }
    visible.value = true;
}

/**
 * 下载
 * @param row
 */
const download = (index) => {
    let fileUrlKey = form.opinionFiles[index].fileUrlKey;
    reserveInvestmentProjectLibraryApi.getPlanWord({templateUrlKey:fileUrlKey}).then(res=>{
        if(res){
            let fileName = fileUrlKey.split('/')[3].split('.')[0];
            let blobType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8';
            exportFile(res,fileName,'docx',blobType);
        }
    });
}

defineExpose({
    open
});
</script>

<style lang="scss" scoped>
.input-width {
    width: 548px;
}
.download-icon{
    color: #fc7037;
    cursor: pointer;
    text-decoration:underline;
}
</style>